<template>
  <a-card :bordered="false">
    <div class="card-title">{{ $route.meta.title }}</div>
    <div class="table-operator">
      <!-- 搜索板块 -->
      <a-row class="row-item-search">
        <a-form class="search-form" :form="searchForm" layout="inline" @submit="handleSearch">
          <a-form-item label="姓名|手机">
            <a-input v-decorator="['search']" placeholder="请输入手机号|姓名" />
          </a-form-item>
          <a-form-item label="经销商等级">
            <a-select v-decorator="['gradeId', { initialValue: 0 }]">
              <a-select-option :value="0">全部</a-select-option>
              <a-select-option
                v-for="(item, index) in gradeList"
                :key="index"
                :value="item.grade_id"
              >{{ item.name }}</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="审核状态">
            <a-select v-decorator="['is_check', { initialValue: -1 }]">
              <a-select-option :value="-1">全部</a-select-option>
              <a-select-option :value="0">未审核</a-select-option>
              <a-select-option :value="1">已审核</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="注册时间">
            <a-range-picker format="YYYY-MM-DD" v-decorator="['betweenTime']" />
          </a-form-item>
          <a-form-item class="search-btn">
            <a-button type="primary" icon="search" html-type="submit">搜索</a-button>
            <a-button type="primary" icon="add" @click="handleAdd()">添加经销商</a-button>
          </a-form-item>
        </a-form>
      </a-row>
    </div>
    <s-table
      ref="table"
      rowKey="user_id"
      :loading="isLoading"
      :columns="columns"
      :data="loadData"
      :pageSize="15"
    >
      <!-- 经销商头像 -->
      <span slot="avatar_url" slot-scope="text">
        <div class="avatar">
          <img v-if="text" width="45" height="45" :src="text" alt="用户头像" />
          <img v-else width="45" height="45" src="~@/assets/img/default-avatar.png" alt="用户头像" />
        </div>
      </span>
      <span slot="main_info" slot-scope="item">
        <p v-if="item.dealer_user[0]">{{ item.dealer_user[0].real_name}}</p>
        <p v-else>{{ item.nick_name }}</p>
        <p class="c-p">{{ item.mobile }}</p>
      </span>
      <!-- 经销商等级 -->
      <span slot="grade" slot-scope="text">
        <a-tag v-if="text">{{ text.name }}</a-tag>
        <span v-else>--</span>
      </span>
      <!-- 余额/积分 -->
      <span slot="balance" slot-scope="text, item">
        <p>
          <span>余额：</span>
          <span class="c-p">{{ text }}</span>
        </p>
        <p>
          <span>积分：</span>
          <span class="c-p">{{ item.points }}</span>
        </p>
      </span>
      <!-- 实际消费金额 -->
      <span slot="expend_money" slot-scope="text">
        <span class="c-p">{{ text }}</span>
      </span>
      <!-- 注册来源 -->
      <span slot="platform" class="platform" slot-scope="text">
        <p v-if="PlatformIcons[text]">
          <a-tooltip>
            <template slot="title">{{ PlatformName[text] }}</template>
            <a-icon class="icon" :class="[text]" :component="PlatformIcons[text]" />
          </a-tooltip>
        </p>
        <p v-else>
          {{text}}
        </p>
      </span>
      <!-- 操作 -->
      <span class="actions" slot="action" slot-scope="item">
        <a v-if="item.is_check!=1" title="经销商审核" v-action:audit @click="handleAuditCheck(item)">审核</a>
        <a title="经销商充值" v-action:recharge @click="handleRecharge(item)">充值</a>
        <a title="经销商等级" v-action:grade @click="handleGrade(item)">等级</a>
		<a title="授权商品"  v-action:recharge @click="handleAccreditGoods(item)">授权</a>
        <a title="重置密码" v-action:grade @click="handlePassword(item)">重置密码</a>
        <a v-action:delete @click="handleDelete(item)">删除</a>
      </span>
      <span class="actions" slot="actioncopn" slot-scope="item">
          <a v-if="item.is_check>=1" title="查看团队" v-action:td @click="handleTd(item)">{{item.team_num}}查看团队</a>
      </span>
      
    </s-table>
    <GradeForm ref="GradeForm" :gradeList="gradeList" @handleSubmit="handleRefresh" />
    <AuditCheck ref="AuditCheck" @handleSubmit="handleRefresh" />
    <RechargeForm ref="RechargeForm" @handleSubmit="handleRefresh" />
    <AddForm ref="AddForm" :dealerList="dealerList" :gradeList="gradeList" @handleSubmit="handleRefresh" />
    <AformForm ref="AformForm" :dealerList="dealerList" @handleSubmit="handleRefresh" />
	<GoodsModal
	  ref="GoodsModal"
	  :multiple="multiple"
	  :maxNum="maxNum"
	  :defaultList="accreditGoodsList"
	  @handleSubmit="handleSelectGoodsSubmit"
	/>
  </a-card>
</template>

<script>
import * as Api from '@/api/user'
import * as GradeApi from '@/api/user/grade'
import { STable, SelectGoods } from '@/components'
import { GradeForm, RechargeForm ,AuditCheck,AddForm,AformForm} from './modules'
import { mpweixin, h5, app } from '@/core/icons'

import * as dealerApi from '@/api/dealer/user'
import * as applyApi from '@/api/dealer/apply'
import * as goodsApi from '@/api/goods'
import { GoodsModal } from '@/components/Modal'
import PropTypes from 'ant-design-vue/es/_util/vue-types'
// 注册来源名称
const PlatformName = {
  'MP-WEIXIN': '微信小程序',
  'H5': 'H5',
  'APP': 'APP'
}

// 注册来源图标
const PlatformIcons = {
  'MP-WEIXIN': mpweixin,
  'H5': h5,
  'APP': app,
}

export default {
  name: 'Index',
  components: {
    STable,
    GradeForm,
    RechargeForm,
    AuditCheck,
    AddForm,
    AformForm,
	SelectGoods,
	GoodsModal
  },
  props: {
    // 多选模式, 如果false为单选
    multiple: PropTypes.bool.def(true),
    // 最大选择的数量限制, multiple模式下有效
    maxNum: PropTypes.integer.def(100),
    // 默认选中的商品
    defaultList: PropTypes.array.def([])
  },
  data () {
    return {
      // 注册来源名称
      PlatformName,
      // 注册来源图标
      PlatformIcons,
      // 当前表单元素
      searchForm: this.$form.createForm(this),
      // 查询参数
      queryParam: {},
      // 正在加载
      isLoading: false,
      // 表头
      columns: [
        {
          title: '经销商ID',
          dataIndex: 'user_id'
        },
        {
          title: '经销商头像',
          dataIndex: 'avatar_url',
          scopedSlots: { customRender: 'avatar_url' }
        },
        {
          title: '名称/手机号',
          scopedSlots: { customRender: 'main_info' }
        },
        {
          title: '团队列表',
          // dataIndex: 'action',
          scopedSlots: { customRender: 'actioncopn' }
        },
        {
          title: '经销商等级',
          dataIndex: 'grade',
          scopedSlots: { customRender: 'grade' }
        },
        {
          title: '余额/积分',
          dataIndex: 'balance',
          scopedSlots: { customRender: 'balance' }
        },
        {
          title: '实际消费金额',
          dataIndex: 'expend_money',
          scopedSlots: { customRender: 'expend_money' }
        },
        // {
        //   title: '注册来源',
        //   dataIndex: 'platform',
        //   scopedSlots: { customRender: 'platform' }
        // },
        {
          title: '邀请人',
          dataIndex: 'dealer_real_name_jj'
        },
        {
          title: '注册时间',
          dataIndex: 'create_time'
        },
        {
          title: '账号审核',
          dataIndex: 'is_check_name'
        },
        {
          title: '操作',
          // dataIndex: 'action',
          width: '180px',
          scopedSlots: { customRender: 'action' }
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: param => {
        return Api.list({ ...param, ...this.queryParam })
          .then(response => {
            return response.data.list
          })
      },
      // 经销商等级列表
      gradeList: [],
      dealerList:[],//注册为经销商列表
	  // 授权商品列表
	  accreditGoodsList: [],
	  accreditGoodsIds: [],
	  accreditUserId:0,
    }
  },
  created () {
    // 获取经销商等级列表
    this.getGradeList()
    
    // 获取经销商列表
    this.getdealerList();
	// 获取授权商品列表
	// this.getAccreditGoodsList();
  },
  methods: {

    // 获取经销商等级列表
    getGradeList () {
      GradeApi.all().then(result => {
        this.gradeList = result.data.list
      })
    },
    // 获取经销商列表
    getdealerList () {
      dealerApi.all({type:2}).then(result => {
        this.dealerList = result.data.list
      })
    },
	// 获取授权商品列表
	async getAccreditGoodsList(accredit_goods) {
		this.isLoading = true
		await goodsApi.list({accredit:1,status:10,accredit_goods:accredit_goods}).then(result => {
		  this.accreditGoodsList = result.data.list.data
		}).finally(() => {
          this.isLoading = false
        })
	},

    // 修改经销商等级
    handleGrade (item) {
      this.$refs.GradeForm.handle(item)
    },
    
    // 查看团队
    handleTd (item) {
       // 跳转到团队那里查看
         this.$router.push({ path: '/apps/dealer/user?search='+item['mobile'] })
    },
	// 获取用户申请授权商品列表
    async handleAccreditGoods(item){
		this.accreditUserId = item.user_id
		this.accreditGoodsList = []
		if(item.accredit_goods != null){
			if(Array.isArray(item.accredit_goods)){
				item.accredit_goods.length &&  await this.getAccreditGoodsList(item.accredit_goods);
			}
		}
		this.$nextTick(()=>{
			this.$refs.GoodsModal.handle(1)
		})
	},
	// 修改用户申请授权的商品
	handleSelectGoodsSubmit(result){
		this.isLoading = true
		applyApi.accredit({userId:this.accreditUserId, form:{accredit_goods:result.selectedRowKeys}}).then(res => {
		  this.$message.success(res.message, 1.5)
		  	this.handleRefresh(false)
		}).finally(() => {
		  this.isLoading = false
		})
	},
	handlePassword(item){
		const app = this
		const modal = this.$confirm({
		  title: '您确定要重置该用户的密码吗?',
		  content: '重置后不可恢复',
		  onOk () {
		    return Api.password({ userId: item.user_id })
		      .then((result) => {	
		        app.$message.success(result.message, 1.5)
		      })
		      .finally(result => {
		        modal.destroy()
		      })
		  }
		})
	},
    // 经销商充值
    handleRecharge (item) {
      this.$refs.RechargeForm.handle(item)
    },
    
    // 经销商添加
    handleAdd () {
      console.log('添加');
      // return;
      this.$refs.AddForm.handle()
    },
    // 经销商审核
    handleAuditCheck (item) {
      console.log('item')
      console.log(item)
      this.$refs.AuditCheck.handle(item)
    },

    /**
     * 删除记录
     */
    handleDelete (item) {
      const app = this
      const modal = this.$confirm({
        title: '您确定要删除该记录吗?',
        content: '删除后不可恢复',
        onOk () {
          return Api.deleted({ userId: item.user_id })
            .then((result) => {
              console.log('result');
              console.log(result);
              if(result.message=='您下面还有团队,需要平移到其他账号')
              {
                // 弹窗出选择邀请人的
                
                  app.$refs.AformForm.handle(item)
                  return;
              }
              
              
              app.$message.success(result.message, 1.5)
              app.handleRefresh()
            })
            .finally(result => {
              modal.destroy()
            })
        }
      })
    },

    // 确认搜索
    handleSearch (e) {
      e.preventDefault()
      this.searchForm.validateFields((error, values) => {
        if (!error) {
          this.queryParam = { ...this.queryParam, ...values }
          this.handleRefresh(true)
        }
      })
    },

    /**
     * 刷新列表
     * @param Boolean bool 强制刷新到第一页
     */
    handleRefresh (bool = false) {
      this.$refs.table.refresh(bool)
    }

  }
}
</script>

<style lang="less" scoped>
  .search-btn button{
    margin-right:30px
  }
.ant-card-body {
  padding: 22px 29px 25px;
}
.platform {
  .icon {
    font-size: 17px;
  }

  .MP-WEIXIN {
    color: #04be02;
  }
  .H5 {
    color: #e44c27;
  }
}
</style>
